import logging
import os
from logging.handlers import TimedRotatingFileHandler

import yaml
from playhouse.pool import PooledMySQLDatabase
from playhouse.shortcuts import ReconnectMixin

# 读取YAML配置文件
with open('config.yaml', 'r') as file:
    config = yaml.safe_load(file)

project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 构建日志文件的完整路径
log_file_path = os.path.join(project_root, 'crypto_trade_order.log')
# 创建一个日志器
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# 创建 TimedRotatingFileHandler
handler = TimedRotatingFileHandler(
    log_file_path,
    when="midnight",
    interval=1,
    backupCount=5
)
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))


# 将处理程序添加到日志器
# logger.addHandler(handler)  # 如果需要输出到屏幕就把这行代码注释掉

# 实现这个类可以避免崩溃
class ReconnectMySQLDatabase(ReconnectMixin, PooledMySQLDatabase):
    pass


# 读取源数据库
def get_db_o():
    base_config_o = config['database_o']
    db_o = ReconnectMySQLDatabase(base_config_o['db'], host=base_config_o['host'], port=base_config_o['port'],
                                  user=base_config_o['user'], password=base_config_o['password'])
    return db_o


# 读取新数据库
def get_db_n():
    base_config_n = config['database_n']
    db_n = ReconnectMySQLDatabase(base_config_n['db'], host=base_config_n['host'], port=base_config_n['port'],
                                  user=base_config_n['user'], password=base_config_n['password'])
    return db_n
